package ro.asterix;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DateServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
		{
			// instantiate the calendar and get the instance
			java.util.Calendar cal = java.util.Calendar.getInstance();

			//create a date format 
			DateFormat df = new SimpleDateFormat( "dd/MM/yy HH:mm:ss" );
			
			// obtaining the formated date
			String formattedDate = df.format(cal.getTime()); 
			
			res.setContentType( "text/plain" );			
			res.addHeader( "Refresh", "1" );
			
			ServletOutputStream out = res.getOutputStream();
			out.println( formattedDate );
			
			// used just for debugging
//			System.out.println( "Date: " +  formattedDate );
//			if ( formattedDate.substring( formattedDate.length()-1 ).equals( "0" ) ) 
			
//			while(true)
//			{
//				
//				if ( formattedDate.lastIndexOf( "0" ) == ( formattedDate.length() - 1 ) ) 
//				{
//					res.addHeader( "Refresh", "5" );	
//					ServletOutputStream out = res.getOutputStream();
//					out.println( formattedDate );
//				}else{
//					res.addHeader( "Refresh", "5" );
//				}
//			}
			
		}
	
	public String getServletInfo(){
		return "Returns a string representation of the current time";
	}
}
